package com.utils.report;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.utils.report.ExcelPrint;
import com.utils.report.ExcelUtil;

/**
 * excle上传通用实现基类
 * @author mapei
 *
 */
public abstract class ExcelUploadBase extends ExcelUpload{
	private static final Logger logger = Logger.getLogger(ExcelPrint.class);
	protected HttpServletRequest request;
	protected HttpSession session;
	private String templatepath;//模版路径
	private String ignore_cols="";//忽略的列   例:col1,col2
	protected String upload_sets;//上传设置  
	private Map<String,String> validate_sets;//验证配置
	private int maxcount=5000;//设置上传最大行数 默认5000行
	protected StringBuffer retmsg=new StringBuffer();//返回消息
	protected int count = 0;// 上传总数
	protected int failure = 0;//失败数
	protected FileUpload fu;//上传文件组件
	protected String[] heads;//列头数据
	
	public ExcelUploadBase(){
		
	}

	public ExcelUploadBase(FileUpload fu,HttpServletRequest request, HttpSession session,
			String templatepath, String ignore_cols, 
			String upload_sets, Map<String,String> validate_sets,int maxcount) {
		this.fu = fu;
		this.request = request;
		this.session = session;
		this.templatepath = templatepath;
		this.ignore_cols = ignore_cols;
		this.upload_sets = upload_sets;
		this.validate_sets = validate_sets;
		this.maxcount = maxcount;
	}

	@Override
	public void upload() {
		String msg = "";//上传错误详细信息
		try {
			boolean isOn = true;
			File srcfile = null;
			if(this.fu.getSaveUrls()!=null && this.fu.getSaveUrls().size()>=1){
				srcfile = new File(this.fu.getSaveUrls().get(0).get("saveUrl"));
				if(!srcfile.exists()){
					retmsg.append("上传失败！上传文件不存在！");
					isOn = false;
				}
			}else{
				retmsg.append("文件上传失败！");
				isOn = false;
			}
			
			//模版的检查
			if(isOn && !"".equals(this.templatepath)){
				File tempfile = new File(this.templatepath);
				if(tempfile.exists()){//如果模板存在
					//验证列头是否匹配
					int tempcols = 0;
					try {
						tempcols = ExcelUtil.getHeadCols(tempfile);
					} catch (Exception e) {
						e.printStackTrace();
					}
					int srccols = 0;
					try {
						srccols = ExcelUtil.getHeadCols(srcfile);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(tempcols!=srccols){//列数不一样
						this.retmsg.append("模版不是最新的，请重新下载！");
						isOn = false;
					}else{
						String tempheads = ExcelUtil.getHeadCons(tempfile);
						String srcheads = ExcelUtil.getHeadCons(srcfile);
						if(!tempheads.equals(srcheads)){
							this.retmsg.append("模版不符合，请重新下载！");
							isOn = false;
						}else{
							String[] headCons = ExcelUtil.getHeads(srcfile);
							if(headCons!=null && headCons.length>0){
								this.heads = headCons;
							}
						}
					}
				}else{//模板路径不存在
					this.retmsg.append("模板路径配置错误！请核对模板路径！");
					isOn = false;
				}
			}
			
			//上传配置检查
			if(isOn && (this.upload_sets==null 
				|| StringUtils.isEmpty(this.upload_sets))
					){
				this.retmsg.append("上传失败！上传配置不完善！");
			}
			
			//上传数据验证
			if(isOn){
				String[][] datas = ExcelUtil.ExcelDataToJson2(srcfile, ignore_cols);
				if(datas==null || datas.length==0){
					this.retmsg.append("上传失败！上传数据为空！");
					isOn = false;
				}else if(datas!=null && datas.length>this.maxcount){
					this.retmsg.append("上传失败！上传数据超过最大"+this.maxcount+"行限制！");
					isOn = false;
				}else{
					Map params = new HashMap();
					count=datas.length;
					for(int i = 0; i < datas.length; i++){
						String[] data = datas[i];
						if(checkIsBlank(data)){
							continue;
						}
						boolean isOk = true;
						for(int j = 0;j < data.length;j++){
							if(isOk){
								if(null==data[j]){
									data[j]="";
								}
								
								params.put("col"+j,data[j]);
							}else{
								break;
							}
						}
						String temp_msg = msg;
						if(isOk){
							//数据处理部分开发人员自行重写
							temp_msg = doData(params);
						}else{
							this.failure++;
						}
						if(!"".equals(temp_msg)){
							this.retmsg.append("第"+(i+2)+"行");
							this.retmsg.append(temp_msg);
							this.retmsg.append("<br/><br/>");
						}
						msg="";
					}
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	
	/**
	 * 往数据库协写数据
	 * @param hh 第几行
	 * @param params 第几行数据
	 * @return
	 */
	public abstract String doData(Map params);
	
	/**
	 * 自定义验证
	 * @param key 验证key
	 * @param datarow 整行数据
	 * @param data 验证列数据
	 * @return
	 */
	public abstract String checkData(String key,String[] datarow,String data);
	/**
	 * 单行数据是否为空的检查
	 * @param data
	 * @return
	 */
	private static boolean checkIsBlank(String[] data){
		boolean isblank = true;
		for(String str:data){
			if(!"".equals(str)){
				isblank = false;
				break;
			}
		}
		return isblank;
	}

	public FileUpload getFu() {
		return fu;
	}

	public void setFu(FileUpload fu) {
		this.fu = fu;
	}

	public StringBuffer getRetmsg() {
		return retmsg;
	}

	public void setRetmsg(StringBuffer retmsg) {
		this.retmsg = retmsg;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public int getFailure() {
		return failure;
	}

	public void setFailure(int failure) {
		this.failure = failure;
	}

	public int getMaxcount() {
		return maxcount;
	}

	public void setMaxcount(int maxcount) {
		this.maxcount = maxcount;
	}

	public String getTemplatepath() {
		return templatepath;
	}

	public void setTemplatepath(String templatepath) {
		this.templatepath = templatepath;
	}

	public String getIgnore_cols() {
		return ignore_cols;
	}

	public void setIgnore_cols(String ignore_cols) {
		this.ignore_cols = ignore_cols;
	}

	public String getUpload_sets() {
		return upload_sets;
	}

	public void setUpload_sets(String upload_sets) {
		this.upload_sets = upload_sets;
	}

	public Map<String,String> getValidate_sets() {
		return validate_sets;
	}

	public void setValidate_sets(Map<String,String> validate_sets) {
		this.validate_sets = validate_sets;
	}

	public HttpServletRequest getRequest() {
		return this.request;
	}
	
	public void setRequest(HttpServletRequest request) {
		this.request = request;
		this.session=this.request.getSession();
	}

	public String getParameterFromRequest(String param_name) {
		if (this.request == null)
			return null;
		return this.request.getParameter(param_name);
	}

	public Object getAttributeFromSession(String attribtue_name) {
		if (this.session == null)
			return null;
		return this.session.getAttribute(attribtue_name);
	}
	
	public String returnmsg(){
		return "<div>上传总数：" + this.count + "<br/><br/>成功数：" + (this.count-this.failure) + "<br/><br/>失败数：" + this.failure + "<br/><br/></div><div style=\"text-align:left;padding-left:5px;\">" + this.retmsg.toString() +"</div>";
	}
}
